/*
 * @Descripttion: 公共组件-一级选项卡下的过滤tab按钮
 * @Author: daxiong
 * @Date: 2021-06-11 15:50:32
 * @LastEditors: daxiong
 * @LastEditTime: 2021-11-23 17:54:33
 */
import React, { useEffect, useState, useRef } from "react";
import { StyleSheet, View, ScrollView, Dimensions, Animated } from "react-native";
import { isEmpty } from "../../utils/helper";
import Button from "../Button";
import { scaleSize } from "../../utils/ScreenUtils";
const { width } = Dimensions.get('window')

const defaultTabs = [{ text: 'tab1', status: 1 }, { text: 'tab2', status: 2 }, { text: 'tab3', status: 3 }, { text: 'tab4', status: 4 }];
let itemLayoutInfo = []; //item布局信息
let scrollW = 0; //scrollView滚动槽总的布局宽度


/**
 * 说明：
 * 1、请勿在将此组件设置为FlatList的ListHeaderComponent。
 * 这样父级渲染时，此组件会被销毁重新渲染，导致onLayout回调每次都执行，定位到被点击的item时会出现闪烁。
 */

/**
 * 属性说明：
 * @param {Array} tabs 按钮列表 [{text:'按钮1',...},{text:'按钮2',...}...]
 * @param {Number} activeIndex 当前选中的索引
 * @param {Function} onPressHandler 按钮item点击事件
 * @param {Object||Array} tabsWrapStyle 组件容器样式
 * @param {Object||Array} itemStyle 按钮item容器样式
 * @param {Object||Array} titleStyle 按钮标题样式
 * @param {Object||Array} activeTitleStyle 选中按钮文字样式
 * @param {Boolean} hasUnderline 是否有下划线，默认有
 */

export default function FilterTabs(props) {
    const {
        tabs, activeIndex, onPressHandler,
        tabsWrapStyle, itemStyle, titleStyle,
        activeTitleStyle, hasUnderline
    } = props || {};

    const ScrollViewRef = useRef();
    const [_tabs, setTabs] = useState([]);
    const [_activeIndex, setActiveIndex] = useState(0);
    const [_hasUnderline, setHasUnderline] = useState(true);
    const underLineAnimation = useRef(new Animated.Value(0)).current;

    useEffect(() => {
        setTabs(isEmpty(tabs) ? defaultTabs : tabs);
        !isEmpty(activeIndex) && setActiveIndex(activeIndex);
        scrollToMethod(activeIndex || 0);
    }, [tabs, activeIndex])

    useEffect(() => {
        !isEmpty(hasUnderline) && setHasUnderline(hasUnderline);
    }, [hasUnderline])

    if (!_tabs) return null;

    function tabsItemEvent({ item, index }) {
        if (_activeIndex == index) return;
        if (typeof onPressHandler == 'function') {
            onPressHandler({ index, item });
        } else {
            setActiveIndex(index);
            scrollToMethod(index);
        }
    }

    function onLayout(layout, index) {
        itemLayoutInfo[parseInt(index)] = layout;
        scrollW += layout.width;
        //最后一个布局完成再开始
        if (index == _tabs.length - 1) {
            console.log('onLayout', layout)
            scrollToMethod(_activeIndex);
        }
    }

    // 返回X方向滚动值
    function resultScrollXValue(index) {
        if (!index) return '请传入item索引';
        let itemLayout = itemLayoutInfo[parseInt(index)];
        let _swidth = width / 2;
        let sx = itemLayout.x - _swidth + itemLayout.width / 2
        return sx;
    }

    // 滚动到具体位置
    function scrollToMethod(index) {
        if (!ScrollViewRef) return;
        if (itemLayoutInfo.length == 0) return;
        let itemLayout = itemLayoutInfo[index];
        if (!itemLayout) return;
        console.log('[itemLayout]', itemLayout)
        let _swidth = width / 2;
        let sx = itemLayout.x - _swidth + (itemLayout.width / 2);
        let lineX = itemLayout.x

        //无需滚动
        if (sx < 0) sx = 0;
        //最后一个，多加50，让scrollView滚到最右边
        if (index == itemLayoutInfo.length - 1) {
            sx += 50;
        }
        //移动位置
        sx < scrollW - _swidth && ScrollViewRef.current.scrollTo({
            x: sx,
            animated: true
        });
        //结尾部分直接移动到底
        sx >= scrollW - _swidth && ScrollViewRef.current.scrollToEnd({
            animated: true
        });
        // console.log('[lineX]', lineX)

        // Animated.timing(underLineAnimation, {
        //     toValue: lineX,
        //     duration: 300,
        // }).start();
    }

    let tabsItemView = [], _activeStyle = {};
    _tabs.map((item, index) => {
        _activeStyle = {};
        if (index == _activeIndex) {
            _activeStyle = [{ fontSize: scaleSize(42), color: '#000', fontWeight: 'bold' }, activeTitleStyle];
        }
        tabsItemView.push(
            <View key={index} onLayout={(res) => { onLayout(res.nativeEvent.layout, index) }} style={{ position: 'relative' }}>
                <Button
                    title={item.text}
                    style={[styles.tabsItem, itemStyle]}
                    textStyle={[styles.tabsTitle, titleStyle, _activeStyle]}
                    onPress={() => tabsItemEvent({ item, index })}
                />
                {
                    index == _activeIndex && _hasUnderline ? (
                        <View style={styles.unerLineWrap}>
                            <View style={styles.underLine} /></View>
                    ) : null
                }
            </View>
        )
    })

    return (
        <View style={[styles.tabsWrap, tabsWrapStyle]}>
            <ScrollView ref={ScrollViewRef} horizontal showsHorizontalScrollIndicator={false} style={{ flex: 1 }}>
                {tabsItemView}
                {/* <Animated.View style={[styles.underLine, { left: underLineAnimation }]} /> */}
            </ScrollView>
        </View>
    )
}


const styles = StyleSheet.create({
    tabsWrap: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: "flex-start",
    },
    tabsItem: {
        minHeight: scaleSize(56),
        alignItems: 'center',
        justifyContent: 'center',
        paddingLeft: scaleSize(30),
        paddingRight: scaleSize(30),
        borderRadius: scaleSize(10),
        paddingBottom: scaleSize(14)
    },
    tabsTitle: {
        color: "#333",
        fontSize: scaleSize(36),
    },
    unerLineWrap: {
        width: '100%',
        alignItems: 'center',
        // position: 'absolute',
        // bottom: 0,
        left: 0,
    },
    underLine: {
        width: scaleSize(60),
        height: scaleSize(10),
        backgroundColor: "#E51809",
        borderRadius: scaleSize(5)
    }
})
